<?php

namespace App\Service\ChatGroup;

use App\Models\ChatGroup\ChatGroupHistoryModel;
use App\Models\ChatGroup\ChatGroupUserModel;
use App\Service\BaseService;
use Illuminate\Support\Facades\DB;

class ChatGroupHistoryService extends BaseService
{
    /**
     * 会话中的聊天记录
     * @param int $shopId
     * @param int $groupId
     * @param int $topMsgId
     * @param int $limit
     * @return array
     */
    public static function getChatHistory(int $shopId, int $groupId, int $topMsgId, int $limit, int $userId): array
    {
        $lists = ChatGroupHistoryModel::query()
                                      ->where('groupId', $groupId)
                                      ->when($shopId, function ($query) use ($shopId) {
                                          $query->where('shopId', $shopId);
                                      })
                                      ->when($topMsgId, function ($query) use ($topMsgId) {
                                          $query->where('id', '<', $topMsgId);
                                      })
                                      ->orderByDesc('id')
                                      ->limit($limit + 1)
                                      ->get()
                                      ->each(function (ChatGroupHistoryModel $item) {
                                          $item->listSenderUid[] = $item->senderUid;
                                      })
                                      ->map(function (ChatGroupHistoryModel $item) {
                                          return $item->getChatStruct();
                                      })->toArray();

        $hasMore = false;
        if (count($lists) == $limit + 1) {
            $hasMore = true;
            array_pop($lists);
        }

        // 倒转
        $lists = array_reverse($lists);

        if ($topMsgId == 0) {
            (new ChatGroupMessageReadService($userId))->readMessage($groupId);
        }

        return ['hasMore' => $hasMore, 'lists' => $lists];
    }

    /**
     * 撤回
     * @param int $id
     * @param int $userId
     * @return void
     */
    public static function recall(int $id, int $userId): void
    {
        $history = ChatGroupHistoryModel::query()->where('id', $id)->first();
        if (!$history) {
            BaseService::throwErr('不存在的消息');
        }

        // 1. 总部的人能撤回
        // 2. 只能自己撤回自己
        $groupId = $history->groupId;

        $kfUser = ChatGroupUserModel::query()
                                    ->where('groupId', $groupId)
                                    ->where('userId', $userId)
                                    ->where('role', ChatGroupUserModel::ROLE_KF)
                                    ->count();
        if (!$kfUser) {
            BaseService::throwErr('只有总部人员才能撤回');
        }

        if ($history->senderUid != $userId) {
            BaseService::throwErr('仅能撤回自己的消息');
        }

        $history->recall    = ChatGroupHistoryModel::RECALL_YES;
        $history->recallUid = $userId;
        $history->save();

        // 发送消息
        (new ChatGroupStructService($groupId, $history->shopId))->recallMsgStruct($id)->send();
    }

    public static function getTextHistoryMsgBySessionId(int $sessionId): array
    {
        $lists = ChatGroupHistoryModel::query()
                                      ->select([
                                          'chat_group_history.id',
                                          'chat_group_history.sessionId',
                                          'chat_group_history.senderUid',
                                          'chat_group_history.content',
                                          'chat_group_history.createdAt',
                                          'chat_group_users.role'
                                      ])
                                      ->leftJoin('chat_group_users', 'chat_group_users.groupId',
                                          'chat_group_history.groupId')
                                      ->whereRaw('chat_group_users.userId = chat_group_history.senderUid')
                                      ->where('sessionId', $sessionId)
                                      ->where('recall', ChatGroupHistoryModel::RECALL_NO)
                                      ->where('type', ChatGroupHistoryModel::TYPE_TEXT)
                                      ->where('isSendAi', ChatGroupHistoryModel::IS_SEND_AI_YES)
                                      ->where('chat_group_users.isDeleted', 0)
                                      ->orderByDesc('chat_group_history.createdAt')
                                      ->limit(50)
                                      ->get()
                                      ->each(function ($item) {
                                          $item->roleText           = ChatGroupUserModel::ROLE_FOR_WHOBOT_MAPPING[$item->role];
                                          $item->createdAtTimestamp = $item->createdAt->timestamp;
                                          unset($item['createdAt']);
                                      })
                                      ->unique('id')
                                      ->reverse()
                                      ->values()
                                      ->toArray();
        return $lists;
    }

    /**
     * 校验是否是最新消息
     *
     * @param $messageInfo
     * @return bool
     */
    public static function checkIsLastMessage($messageInfo): bool
    {
        $count = ChatGroupHistoryModel::query()
                                      ->where('sessionId', $messageInfo->sessionId)
                                      ->where('id', '>', $messageInfo->id)
//                                      ->where('senderUid', $messageInfo->senderUid)
                                      ->count(DB::raw('1'));

        return $count == 0;
    }
}
